<template>
  <div>
    <el-upload
      ref="upload"
      :auto-upload="false"
      :on-exceed="handleExceed"
      :on-change="handleOnChange"
      :on-preview="handlePictureCardPreview"
      :before-remove="handleRemove"
      :limit="limitNum"
      :multiple="multiple"
      :file-list="object.dbFileList"
      style="width: 557px;"
      action="#"
      accept="image/png,image/jpg,image/jpeg,application/pdf"
    >
      <el-button type="text" size="mini" round icon="el-icon-upload2">点击选择上传文件（最多上传10个文件）</el-button>
    </el-upload>
    <preview ref="previewRef" />
  </div>
</template>

<script>
import { uploadFile, removeFile } from '@/api/file'
import preview from '@/views/preview/index'

export default {
  components: { preview },
  props: {
    object: {
      type: Object,
      default: () => { return { dbFileList: [] } }
    }
  },
  data() {
    return {
      limitNum: 10,
      multiple: true,
      cerfileList: [],
      delUrlList: []
    }
  },
  methods: {
    // 文件变动的钩子
    handleOnChange(file, fileList) {
      if (!(file.raw.type === 'image/png' || file.raw.type === 'application/pdf' || file.raw.type === 'image/jpg' || file.raw.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为png, jpg, jpeg的图片, 或者pdf文件。'
        })
        fileList.pop()
      }
      var size = file.size / 1024 / 1024
      if (size > 10) {
        this.$notify.warning({
          title: '警告',
          message: '图片大小必须小于10M'
        })
        fileList.pop()
      }
      this.cerfileList = fileList
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      var raw = file.raw ? file.raw : file
      this.$refs.previewRef.handlePictureCardPreview(raw)
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$notify({
        title: '资质文件上传数量限制为：' + this.limitNum,
        type: 'warning',
        duration: 2500
      })
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.object.dbFileList.map(res => {
        if (res.url === file.url) {
          this.object.dbFileList.splice(this.object.dbFileList.indexOf(res), 1)
          this.delUrlList.push(res.url)
        }
      })
    },
    // 上传文件至服务器
    async doUploadFile() {
      return new Promise((resolve, reject) => {
        if (this.cerfileList.length < 1 && this.object.dbFileList.length < 1) {
          this.$notify({
            title: '请上传所需文件。',
            type: 'error',
            duration: 2500
          })
          reject('')
        } else {
          var formData = new FormData()
          this.cerfileList.map(file => {
            formData.append('file', file.raw)
          })
          uploadFile(formData).then(fileUploadResult => { // 上传资质文件
            if (fileUploadResult.code === 0) {
              const urlArray = this.object.dbFileList
              fileUploadResult.successUrls.map(successFile => {
                var successObj = JSON.parse(successFile)
                this.cerfileList.map(file => {
                  var raw = file.raw ? file.raw : file
                  if (raw.name === successObj.name) {
                    successObj.type = raw.type
                  }
                })
                urlArray.push(successObj)
              })
              removeFile(this.delUrlList).then(() => { // 删除服务器中被删除的资质文件
                resolve(urlArray)
              })
            } else {
              var errorMsg = ''
              fileUploadResult.errorMsgs.map(eMsg => {
                errorMsg = errorMsg + eMsg + '\n'
              })
              this.$alert(errorMsg, '错误提示', {
                confirmButtonText: '确定'
              })
              reject('')
            }
          })
        }
      })
    },
    // 清理缓存
    cancel() {
      this.delUrlList = []
      this.cerfileList = []
      this.object.dbFileList = []
      this.$refs.upload.clearFiles()
    }
  }
}
</script>
